//initiailzie stuff when document is ready
$(document).ready(function() {
	// gets username
	var username = gup("id");
	//alert(username);  // testing field
	
	// a hash map to return the username
	$("#data").data("username", username);
	
	USER_ID = $("#data").data("username");
	
	//get the buddy list
	getBuddyList();
	sendStatus(1);
	
	//make the buddy list window draggable
	$("#buddyList").draggable({"handle" : ".buddyHandle"});
	
	//event handler for the add buddy button
	$("#addBuddyBtn").click(function() {
		addBuddy();
	});
	
	//event handler for the remove buddy button
	$("#delBuddyBtn").click(function() {
		removeBuddy();
	});
	
	eventListener();
});


//This is the URL for the IM server we are sending and recieving from
//Note that the page this script is loaded from must be on the same domain as the URL the data is being sent to, otherwse you will get an ajax permission denied error.	
var IM_URL = "/pimp/WebResponder";

//This is my user id - assume this eventually comes from a loin somehwere
//var USER_ID = "james";
//var USER_ID = $("#data").data("username");
var USER_ID;

//Initialize jquery ajax to wait for a server response instead of the default asyncronous send, and set the URL of the IM server
$.ajaxSetup({
	async: false,
	url : IM_URL
});
	
var zindex = 1;

var initOffset = 10;
var initXY = 100;

//An array that contains the current list of buddies. Each entry is a buddy object which consists of an object with an id and a status.
var buddyList = [];

/*******************************************************************
* Put some dummy buddies in the list so I can test it, remove this later
********************************************************************/
/*
buddyList.push( { id : "james", status : 1 });
buddyList.push( { id : "hi", status : 1 });
buddyList.push( { id : "hello", status : 0 });
buddyList.push( { id : "joe", status : 1 });
buddyList.push( { id : "abc", status : 1 });
buddyList.push( { id : "blahbla", status : 1 });
buddyList.push( { id : "qweqwe", status : 1 });
buddyList.push( { id : "xvcdcz", status : 1 });
buddyList.push( { id : "safddf", status : 1 });
*/





// gets url parameters
function gup( name )
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if (results == null)
		return "";
	else
		return results[1];
}

//create a new chat window with the given id and title
function showWindow(id, title)
{

	//get the template HTML for a new IM window
	var newHtml = $("#buddyTemplate").html();

	var newId = 'buddy_' + id;
	
	//if the window exists but was hidden, just show it and exit
	if ( $("#" + newId).length>0 ) {
		$("#" + newId).show();
		return;
	}
	

	//set the new ID to something unique
	newHtml = newHtml.replace("budId", newId );

	//add the new window to the page
	$("#container").append(newHtml);
	var sNewId = "#" + newId;

	//set the new window's title and make it draggable
	$(sNewId + " .buddyTitle").text(title);
	$(sNewId).draggable({"handle" : ".buddyHandle"});

	//offset the new window's position and show it
	$(sNewId).css("left", initXY + "px");
	$(sNewId).css("top", initXY + "px");
	initXY += initOffset;
	$(sNewId).show();
	$(sNewId + " .chatEntry").focus();

	
	//Add event handler for enter key in the IM chat entry box
	//This will put the message entered in the IM buddy chat window and call sendMessage() to send message to server
	$(sNewId + " .chatEntry").keyup( function(e) {
		if (e.which == 13) {
			var budChat = $(this).siblings(".budChat");
			var messageText = $(this).val();
			var d = new Date();
			
			//alert("message Text:"+ messageText);

			var div = $("<div class='chatLine'><em>"+d.toLocaleTimeString()+"</em> "+USER_ID+": <strong>"+messageText+"</strong></div>");
			//append the entered text to the buddy chat box
			budChat.append(div);
			budChat.scrollTo(budChat.find(".chatLine:last").get(0));
			
			//clear the IM chat entry box
			$(this).val("");
			
			//construct the IM message to send
			var message = new Object();
			message.userID = USER_ID;
			message.recipientID = title;
			message.message = messageText;
			message.type = 0;
			message.timestamp = new Date();	
			
			//send the message
			sendMessage(message, budChat);
		}
	});


	//IM window mousedown event handler
	//Give chat entry box focus and move window to front when selected
	$(sNewId).mousedown(function() {
		$(this).css("zIndex", zindex++);
		$(sNewId + " .chatEntry").focus();
	});
	
	//Close button event handler
	//This will hide a window when its closeButton is clicked
	$(".closeButton").click( function() {
		$(this).closest(".closeable").hide();
	});

	//increment ID for next window to be created
	//id++;
}


//Sends a message to the server.
//Waits for a response and returns 0 on failure or 1 on success (but it also alerts the error message).
function sendMessage(message, budChat)
{							
	var userID = message.userID;
	var recipientID = message.recipientID;
	var message = message.message;

	var status = 0;
	try	{
		//send the message to the remote URL, using the URL set above in ajaxSetup()
		$.ajax({
			data : "&type=sendmessage&to="+recipientID+"&from="+USER_ID+"&message="+message,
			success : function(responseData, textStatus) {
				if (responseData != 1) {
					budChat.append("<span style='color: red; font-style: italic'>Error sending message: Code "+responseData+"</span>");
				}
			},
			error : function(x,t,r) {
				if (t !=null) throw(t);
				else if (r != null) throw(r);
			}
		});
	}
	catch (e) {
		//catch permission denied error
		alert("Error sending message: " + e);
	}			
	return status;
}


//Gets a buddy list from the remote URL, using the URL set above in ajaxSetup(), then updates the global buddy ist variable and the buddy list window
function getBuddyList()
{
	try	{
		//send the userID to the remote URL, using the URL set above in ajaxSetup()
		//NOTE: the data being sent is just the userId currently.
		//The URL and/or the data will need changing so the server understands this is a buddy list request
		
		// alert("2");	testing field
		$.ajax({
			//url: "http://tornado.ics.uci.edu:8080/pimp/WebResponder?&type=getbuddylist&clientID="+$("#data").data("username"),
			//url: "http://tornado.ics.uci.edu:8080/pimp/WebResponder?&type=getbuddylist&clientID="+USER_ID,
			//url: IM_URL + "?&type=getbuddylist&clientID=" + USER_ID,
			data: "type=getbuddylist&clientID="+USER_ID,
			dataType: "json", //assuming that the buddy list returned is in json format
			success : function(responseData, textStatus) {
				if (textStatus == "success") {
					//set the global buddyList to the returned  data
					buddyList = responseData.buddylist; //assumes that the response data is an object that is an array of buddies as described above for the buddyList global
					//and update the displayed list from the buddyList
					updateBuddyList();
				}
				else throw(textStatus);
			},
			error : function(x,t,r) {
				if (t !=null) throw(t);
				else if (r != null) throw(r);
			}
		});
	}
	catch (e) {
		//catch permission denied error
		alert("Error getting buddy list: " + e);
	}

}



//Adds a buddy to the buddy list window.
//Prompts for the buddy id, then it sends a request to the server to get the buddy status.
//If the server responds that the specified buddy exists, then it adds it to the list
function addBuddy()
{	
	//Prompt for the buddy to add
	var buddyId = window.prompt("Enter the buddy id to add:");
	if (buddyId == null || buddyId.length==0) return;
	
	
	/*********************************************************/
	// Just for testing - remove this section when comm works
//	buddyList.push( {id : buddyId, status : 1} ); 
//	updateBuddyList();
//	return;
	/*********************************************************/
	
	
	//send the message to the remote URL, using the URL set above in ajaxSetup()
	//NOTE: the data being sent is just the userId currently, 
	//The URL and/or the data will need changing so the server understands this is an add buddy request, and to add the buddy info to the request
/*	$.ajax({
		//data : USER_ID, //add something here to indicate this is an add buddy request and include the buddyId
		data: "&type=addbuddy&clientID="+USER_ID+"&buddy="+buddyId+"&group=default",
		success : function(responseData, textStatus) {
			//if server sends back any successful status, then assume this means that this buddy is valid, so go ahead and add its
			if (responseData == 1) { 
				//This is where we add the new buddy to the global buddy list
				//The status for the newly added buddy should be set to whatever the server returns, but just setting to 1 for now
				buddyList.push( {id : buddyId, status : 0} );
				//TODO: get status for this buddy
				//And then update the displayed list
				updateBuddyList();
			}
			else throw(textStatus);
		},
		error : function(x,t,r) {
			if (t !=null) throw(t);
			else if (r != null) throw(r);
		}
		
	});	
*/

		$.get(IM_URL+"?&type=addbuddy&clientID="+USER_ID+"&buddy="+buddyId.toLowerCase()+"&group=default", function(data){
			if (data ==1){
			//success 
				buddyList.push( {id : buddyId, status : 0} );
				updateBuddyList();
				getBuddyList();
			} else {
				alert ("No User Exists\nerror code: "+data);
			}
		});
}

//Removes the highlighted buddy from the buddy list window
function removeBuddy()
{

	var selectedBuddy = $("#buddies .selected");
	//should only be 1 selected, if none, then do nothing
	if (selectedBuddy.length != 1) return;
	var buddyId = selectedBuddy.attr('id');
	
	/****************************************************************************************************
	// Just for testing - remove this section when comm works
	$.each(buddyList, function(i, val) {
		//if the selected id matches the current is in the list, remove it from the buddyList array and return
		if (buddyId == val.id) {
			buddyList.splice(i, 1);
			return false;
		}
	});
	//update the visual list
	updateBuddyList();
	//and hide any buddy window with this id (really should remove it entirely, but this is ok for now
	$("#buddy_" + buddyId).hide();
	return;
	*****************************************************************************************************/
	
	
	//send the message to the remote URL, using the URL set above in ajaxSetup()
	//NOTE: the data being sent is just the userId currently, 
	//The URL and/or the data will need changing so the server understands this is a remove buddy request, and to add the buddy info to the request
/*	$.ajax({
		data : "type=removebuddy&clientID="+USER_ID+"&buddy="+buddyId+"&group=default",
		success : function(responseData, textStatus) {
			//doesnt matter what the server sends back - we will go ahead and remove it from our list anyway
			if (responseData == 1) { 
				$.each(buddyList, function(i, val) {
					//if the selected id matches the current is in the list, remove it from the buddyList array and return
					if (buddyId == val.id) {
						buddyList.splice(i, 1);
						return false;
					}
				});
				//update the visual list
				updateBuddyList();
				//and hide any buddy window with this id (really should remove it entirely, but this is ok for now
				$("#buddy_" + buddyId).hide();
			} else {
				//throw(textStatus);
			}
		},
		error : function(x,t,r) {
			if (t !=null) throw(t);
			else if (r != null) throw(r);
		}

	});	
	*/
	$.get(IM_URL+"?&type=removebuddy&clientID="+USER_ID+"&buddy="+buddyId.toLowerCase()+"&group=default", function(data){
			if (data == 1){
				//success
				$.each(buddyList, function(i, val) {
					//if the selected id matches the current is in the list, remove it from the buddyList array and return
					if (buddyId == val.id) {
						buddyList.splice(i, 1);
						return false;
					}
				});
				//update the visual list
				updateBuddyList();
				//and hide any buddy window with this id (really should remove it entirely, but this is ok for now
				$("#buddy_" + buddyId).hide();
			} else {
				alert("error. code: "+data);
			}
	});	

	
	
}

//Send the status 
function sendStatus(status)
{
	$.post(IM_URL+"?&type=status&status="+status+"&clientid="+USER_ID);
}


//Helper function to update the displayed buddy list from the global buddy list variable
function updateBuddyList()
{	
	$("#buddies").html("");
	var listHtml = "";
	//for each buddy in the buddyList array, add it in a div tag to the html string
	$.each(buddyList, function(i, val) {
		//add a status class so the entrycould have different appearance depending on status
		var status = "status" + val.status;
		listHtml += "<div id=\"" + val.id + "\" class=\"buddyListId " + status + "\">" + val.id + "</div>";
	});
	//and refresh the buddy list window with the contents of this html string
	$("#buddies").html(listHtml);
	
	//add event handlers for the buddy list id when clicked
	$(".buddyListId").click(function() {
		//remove the selected class for all buddy id's
		$(".selected").css("background-color", "#eef");
		$(".buddyListId").removeClass("selected");
		//and add it to this one thay was just clicked
		$(this).addClass("selected");
	});	
	
	//add event handlers for the buddy list id when double-clicked top open a chat window
	$(".buddyListId").dblclick(function() {
		//show the chat window, make the title and id both the same as the id ofthe buddy
		showWindow($(this).attr('id'), $(this).attr('id'))
	});		

	//scroll to the bottom of buddies window
	var buddiesElement = document.getElementById("buddies");
	buddiesElement.scrollTop = buddiesElement.scrollHeight;
	
	buddyHover();
}

function getHistory(){

	$.get(IM_URL+"?&type=gethistory&clientID="+USER_ID, function(data){
	
	});
}

function buddyHover(){
	$(".buddyListId").hover(function(){
		if ($(this).hasClass("selected")){
			$(this).css("background-color", "#7700bb");
		} else {
			$(this).css("background-color", "#dae8ff");
		}
	},function(){
		if ($(this).hasClass("selected")){
			$(this).css("background-color", "#7700bb");
		} else {
			$(this).css("background-color", "#eef");
		}
	});
}

function eventListener(){
	$.getJSON(IM_URL+"?&type=event&clientid="+USER_ID, function(data){	
		if (data == null){ } else {
			if (data.status == 0){
			} else if (data.status == 1){
				var messages = data.messages;
				updateMessages(messages);
			} else if (data.status == 2){
				//data is just a buddylist
				buddyList = data.buddylist;
				updateBuddyList();
			} else if (data.status == 3){
				var messages = data.messages;
				buddyList = data.buddylist;
				updateMessages(messages);
				updateBuddyList();
			} else {
				//else nothing... I dunno
			}
		}
		setTimeout('eventListener()', 1);
	});
}

function updateMessages(messages){
	//messages is an array
	$.each(messages, function(i, val) {
		var sender = val.sender;
		//var receiver = val.receiver;
		var message = val.text;
		var time = val.time;
		
		if ($("#buddy_"+sender).size() > 0){
			//if the window is already open
			
			//make it appear if it isn't
			//$("#buddy_"+sender)
			$("#buddy_"+sender).css("display", "block");
			addIncomingMessage(sender, message, time);
		} else {
			//make create the window template and add the message
			showWindow(sender, sender);
			addIncomingMessage(sender, message, time);
		}
	});
}

function addIncomingMessage(sender, message, time){
	var d = new Date();
	var chatline = "<div class='chatLine'><em>"+d.toLocaleTimeString()+"</em> "+sender+": <strong>"+message+"</strong></div>";
	$("#buddy_"+sender+" .budChat").append(chatline);
	$("#buddy_"+sender+" .budChat").scrollTo($("#buddy_"+sender+" .budChat").find(".chatLine:last").get(0));
}
